import Vue from 'vue'
import Vuex from 'vuex'
import request from '@/utils/request'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    token: window.sessionStorage.getItem('token'),
    userInfo: JSON.parse(window.sessionStorage.getItem('userInfo')) || {},
  },
  getters: {
    token: state => state.token,
    userInfo: state => state.userInfo,
    userId: state => state.userInfo ? state.userInfo.id : null,
    username: state => state.userInfo ? state.userInfo.username : '',
    name: state => state.userInfo ? state.userInfo.name : '',
    role: state => state.userInfo ? state.userInfo.role : '',
  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token
      window.sessionStorage.setItem('token', token)
    },
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo
      window.sessionStorage.setItem('userInfo', JSON.stringify(userInfo))
    },
    UPDATE_USER_INFO(state, userInfo) {
      state.userInfo = {...state.userInfo, ...userInfo}
      window.sessionStorage.setItem('userInfo', JSON.stringify(state.userInfo))
    },
    RESET_USER(state) {
      state.token = ''
      state.userInfo = {}
      window.sessionStorage.removeItem('token')
      window.sessionStorage.removeItem('userInfo')
    }
  },
  actions: {
    // 登录
    login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        console.log('登录请求参数:', userInfo)
        request.post('/auth/login', userInfo)
          .then(res => {
            console.log('登录响应:', res)
            if (res.code === 200 && res.data) {
              const { token, userInfo: user } = res.data
              console.log('登录成功，保存token和用户信息:', token, user)
              
              // 保存token和用户信息
              commit('SET_TOKEN', token)
              commit('SET_USER_INFO', user)
              
              // 直接保存到sessionStorage（备用方案）
              window.sessionStorage.setItem('token', token)
              window.sessionStorage.setItem('userInfo', JSON.stringify(user))
              
              resolve()
            } else {
              reject(new Error(res.msg || '登录失败'))
            }
          })
          .catch(error => {
            console.error('登录请求失败:', error)
            reject(error)
          })
      })
    },
    // 获取用户信息
    getUserInfo({ commit }) {
      return new Promise((resolve, reject) => {
        request.get('/auth/info')
          .then(res => {
            console.log('获取用户信息响应:', res)
            if (res.code === 200 && res.data) {
              commit('SET_USER_INFO', res.data)
              // 直接保存到sessionStorage（备用方案）
              window.sessionStorage.setItem('userInfo', JSON.stringify(res.data))
              resolve(res.data)
            } else {
              reject(new Error(res.msg || '获取用户信息失败'))
            }
          })
          .catch(error => {
            console.error('获取用户信息请求失败:', error)
            reject(error)
          })
      })
    },
    // 更新用户信息
    updateUserInfo({ commit }, userInfo) {
      commit('UPDATE_USER_INFO', userInfo)
    },
    // 登出
    logout({ commit }) {
      commit('RESET_USER')
    },
    // 重置令牌
    resetToken({ commit }) {
      commit('RESET_USER')
    }
  },
  modules: {
  }
}) 